<template>
  <div class="inform">
    <a-form
        :model="formState"
        v-bind="layout"
        :name="user.id"
        :validate-messages="validateMessages"
        @finish="onFinish"
    >
      <a-form-item label="头像">
        <a-upload
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            action="http://192.168.10.73:8880/user/upload/file"
            :before-upload="beforeUpload"
            @change="handleChange"
        >
          <img v-if="imageUrl" :src="imageUrl" alt="avatar"/>
          <div v-else>
            <loading-outlined v-if="loading"></loading-outlined>
            <plus-outlined v-else></plus-outlined>
            <div class="ant-upload-text">Upload</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item :name="['user', 'name']" label="用户名" :rules="[{ required: true }]">
        <a-input v-model:value="formState.user.name"/>
      </a-form-item>
      <a-form-item :name="['user', 'sex']" label="性别">
        <a-radio-group v-model:value="formState.user.sex">
          <a-radio :value="0">男</a-radio>
          <a-radio :value="1">女</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item :name="['user', 'email']" label="Email" :rules="[{ type: 'email' }]">
        <a-input v-model:value="formState.user.email"/>
      </a-form-item>
      <a-form-item :name="['user', 'age']" label="年龄" :rules="[{ type: 'number', min: 0, max: 99 }]">
        <a-input-number v-model:value="formState.user.age"/>
      </a-form-item>
      <a-form-item :name="['user', 'birthday']" label="生日" v-bind="config">
        <a-date-picker v-model:value="formState.user.birthday" value-format="YYYY-MM-DD"/>
      </a-form-item>
      <a-form-item :name="['user', 'website']" label="个人网址">
        <a-input v-model:value="formState.user.website"/>
      </a-form-item>
      <a-form-item :name="['user', 'introduction']" label="简介">
        <a-textarea :rows="4" :showCount="true" v-model:value="formState.user.introduction"/>
      </a-form-item>
      <a-form-item :wrapper-col="{ ...layout.wrapperCol, offset: 4 }">
        <a-space :size="10">
          <a-button type="primary" html-type="submit">Submit</a-button>
          <a-button type="danger" @click="showPasswordReset">修改密码</a-button>
          <a-button type="Default" @click="back">Cancel</a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </div>
  <a-modal
      v-model:visible="modalVisible"
      :confirm-loading="modalLoading"
      title="修改密码"
      :centered="true"
      :ok-button-props="{ disabled: disable }"
      @ok="handleModalOk"
  >
    <a-form :label-col="{span:6}"
            :model="pass"
            :rules="rules"
    >
      <a-form-item has-feedback label="旧密码" name="oldPassword">
        <a-input v-model:value="pass.oldPassword" type="password" autocomplete="off"/>
      </a-form-item>
      <a-form-item has-feedback label="新密码" name="password">
        <a-input v-model:value="pass.password" type="password" autocomplete="off"/>
      </a-form-item>
      <a-form-item has-feedback label="确认密码" name="checkPass">
        <a-input v-model:value="pass.checkPass" type="password" autocomplete="off"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import {computed, defineComponent, onMounted, reactive, ref} from 'vue';
import axios from "axios";
import store from "@/store";
import {message} from "ant-design-vue";
import router from "@/router";
import PhotoUpload from "@/pages/User/components/PhotoUpload";
import {UploadOutlined, InboxOutlined} from '@ant-design/icons-vue';

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

export default defineComponent({
  name: "UserInfo",
  components: {
    PhotoUpload,
    UploadOutlined,
    InboxOutlined,
  },
  // props:{
  //   id:Number
  // },
  setup() {
    const user = computed(() => store.state.user)
    const layout = {
      labelCol: {
        span: 6,
      },
      wrapperCol: {
        span: 18,
      },
    };
    const validateMessages = {
      required: '${label} is required!',
      types: {
        email: '${label} is not a valid email!',
        number: '${label} is not a valid number!',
      },
      number: {
        range: '${label} must be between ${min} and ${max}',
      },
    };
    const formState = reactive({
      user: {
        id: user.value.id,
        name: '',
        sex: 0,
        age: undefined,
        email: '',
        website: '',
        birthday: '',
        introduction: '',
        photo: user.value.photo
      },
    });

    //头像框
    const fileList = ref([]);
    const imageUrl = ref('');
    imageUrl.value = user.value.photo;
    const loading = ref(false);
    const handleChange = info => {
      if (info.file.status === 'uploading') {
        loading.value = true;
        // console.log("uping", info)
        return;
      }
      if (info.file.status === 'done') {
        console.log("done", info)
        // Get this url from response in real world.
        // getBase64(info.file.originFileObj, base64Url => {
        //   formState.user.photo = base64Url;
        //   user.value.photo = base64Url;
        //   imageUrl.value=base64Url;
        //   loading.value = false;
        // });
        imageUrl.value = info.file.response.content;
        formState.user.photo = info.file.response.content;
        loading.value = false;
        console.log("上传完图片,info", info.file.response.content)
        console.log("上传完图片,formstate", formState.user)
      }
      if (info.file.status === 'error') {
        loading.value = false;
        message.error('upload error');
      }
    };
    const beforeUpload = file => {
      console.log("file", file)
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('You can only upload JPG file!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
      }
      return isJpgOrPng && isLt2M;
    };

    //读取所有用户资料
    async function getUser() {
      let res = await axios.get("http://192.168.10.73:8880/user/one?id=" + user.value.id);
      console.log(user.value.id)
      if (res.data.status === 10000) {
        const data = res.data.content;
        // console.log(res.data)
        formState.user.birthday = data.birthday;
        formState.user.name = data.name;
        formState.user.sex = data.sex;
        formState.user.age = data.age;
        formState.user.website = data.website;
        formState.user.email = data.email;
        formState.user.introduction = data.introduction;
        console.log('user', formState.user)
      }
    }

    const onFinish = () => {
      // console.log('values:', values);
      // console.log('Success:', formState.user);
      axios.post("http://192.168.10.73:8880/user/update", formState.user).then((res) => {
        const data = res.data;
        if (data.status === 10000) {
          console.log("更新用户后", res)
          message.success("保存成功！");
          store.commit("setUser", data.content);
          router.push('/')
        } else {
          message.error(data.msg)
        }
      })
    };

    // const submit=()=>{
    //   console.log('Success:', formState.user);
    //   axios.post("/user/update"+formState.user).then((res)=>{
    //     if (res.data.status===10000){
    //       console.log(res)
    //       message.success("保存成功！")
    //     }
    //   })
    // }

    const back = () => {
      router.push('/')
    }

    //修改密码框
    const formRef = ref();
    const modalVisible = ref(false)
    const modalLoading = ref(false)
    let validatePass = async (_rule, value) => {
      if (value.length < 6) {
        return Promise.reject('密码必须大于6位');
      } else {
        if (pass.checkPass !== '') {
          await formRef.value.validateFields('checkPass');
        }
        return Promise.resolve();
      }
    };
    let validatePass2 = async (_rule, value) => {
      if (value === '') {
        return Promise.reject('请重新输入密码');
      } else if (value !== pass.password) {
        return Promise.reject("两次输入的密码必须一致!");
      } else {
        return Promise.resolve();
      }
    };
    const rules = {
      oldPassword: [{
        required: true,
        message: "请输入旧密码",
        trigger: 'change',
      }],
      password: [{
        required: true,
        // pattern:"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,32}$",
        validator: validatePass,
        trigger: 'change',
      }],
      checkPass: [{
        validator: validatePass2,
        trigger: 'change',
      }]
    };
    const pass = reactive({
      id: user.value.id,
      oldPassword: '',
      password: '',
      checkPass: ''
    })

    const showPasswordReset = () => {
      // console.log("hello")
      modalVisible.value = true;
    }
    const disable = computed(() => {
      return !(pass.oldPassword.length >= 6 && pass.checkPass.length >= 6 && pass.password.length >= 6);
    });

    const handleModalOk = () => {
      if (pass.password !== pass.checkPass) {
        message.error("两次输入的密码不相同，请重新输入");
        modalVisible.value = false;
        pass.checkPass = ''
        pass.password = ''
        pass.oldPassword = ''
      } else {
        axios.post("http://192.168.10.73:8880/user/reset", pass).then((res) => {
          const data = res.data;
          if (data.status === 10000) {
            console.log(res)
            message.success("修改成功！");
            modalVisible.value = false;
            pass.checkPass = ''
            pass.password = ''
            pass.oldPassword = ''
          } else {
            message.error(data.msg)
            modalVisible.value = false;
            pass.checkPass = ''
            pass.password = ''
            pass.oldPassword = ''
          }
        })
      }
    }

    onMounted(() => {
      getUser();
    })

    return {
      fileList,
      imageUrl,
      user,
      formState,
      loading,
      handleChange,
      beforeUpload,
      onFinish,
      layout,
      // submit,
      back,
      validateMessages,
      modalLoading,
      showPasswordReset,
      disable,
      modalVisible,
      pass,
      rules,
      handleModalOk
    };
  },

});
</script>

<style scoped>
.inform {
  width: 80%;
  height: 80%;
  margin-left: 10%;
  margin-top: 20%;
}

img {
  width: 100px;
  height: 100px;
}

.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>